package hasthi.actuators;

import java.util.Arrays;

import hasthi.common.HasthiException;
import hasthi.common.constants.WSDMConstants;
import hasthi.container.MessageContext;
import hasthi.container.SimpleMessageContext;
import hasthi.metamodel.resource.ManagedResource;

import org.apache.xmlbeans.XmlCursor;
import org.apache.xmlbeans.XmlObject;

public class CallOpAction extends ResourceBasedAction{
    private String name;
    private String opName;
    private String[][] params;
    private String soapAction;
    public CallOpAction(ManagedResource resource,String opName,String[][] params, String soapAction) {
        super(resource);
        this.opName = opName;
        this.params = params;
        this.soapAction = soapAction;
        name =  CallOpAction.class.getName()+"|" + resource.getName() + "|" + this.opName + "|" + (params==null?"":Arrays.toString(params)) ;
    }
    
    public String getActionID() {
        return name;
    }

    
    public void execute()throws HasthiException{
        /**
         * request will take the form of opname/param1->param1Val...
         */
        XmlObject request = XmlObject.Factory.newInstance();
        XmlCursor c = request.newCursor();
        c.toFirstContentToken();
        c.beginElement(opName,WSDMConstants.EXTREME_MANAGEMENT_NS);
        //we go from last param to first, to make sure parameters are added in order
        for(int i = params.length -1;i >= 0;i--){
            String [] param = params[i];
            c.beginElement(param[0],WSDMConstants.EXTREME_MANAGEMENT_NS);
            if(param.length > 1){
                c.insertChars(param[1]);    
            }
            c.toParent();
        }
        c.dispose();
        MessageContext message = new SimpleMessageContext(request,resource.getManagerAgentURL(),soapAction);
        actionContext.getUnicastContainer().sendReceive(message);
    }

}
